package com.ruoyi.controller;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.config.emqx.EmqxApiClient;
import com.ruoyi.domain.DeviceEmqxClient;
import com.ruoyi.service.DeviceDataService;
import com.ruoyi.service.DeviceEmqxClientService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * mqtt服务器相关接口,业务暂时不需要
 */
@Controller
@RequestMapping("/emqxapi")
public class EmqxApiController {

    @Resource
    EmqxApiClient emqxApiClient;

    @Resource
    DeviceEmqxClientService deviceEmqxClientService;

    /**
     * 通过发送http请求获取设备在线状态
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getDeviceInfo")
    public Object getDeviceInfo() {
        JSONArray onlineClients = null;
        try {
            System.out.println("开始调用EMQX API获取设备信息...");
            onlineClients = emqxApiClient.getOnlineClients();
            System.out.println("EMQX API返回数据: " + onlineClients);
        } catch (Exception e) {
            System.err.println("调用EMQX API失败: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("获取设备信息失败: " + e.getMessage());
        }
        return AjaxResult.success(onlineClients);
    }

    /**
     * 通过发送http请求添加在线设备信息到数据库
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/add")
    public Object add() throws Exception {
        Integer count = 0;
        // 通过emqx工具类获取目前的设备的信息
        JSONArray onlinCelients = emqxApiClient.getOnlineClients();
        for (int i = 0; i < onlinCelients.size(); i++) {
            DeviceEmqxClient javaObject = onlinCelients.getJSONObject(i).toJavaObject(DeviceEmqxClient.class);
            deviceEmqxClientService.add(javaObject);
            count++;
        }
        return count;
    }
}
